package com.example.chatGPTDemo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Controller
public class Chat {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/api")
    @ResponseBody
    public String chat(@RequestParam("que") String que) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.set("Authorization", "Bearer 你的API Key");
        JSONObject requestBody = new JSONObject();
        // 拼接请求参数
        requestBody.put("prompt", que);
        requestBody.put("max_tokens", 2048);
        requestBody.put("temperature", 1);
        requestBody.put("model", "text-davinci-003");
        HttpEntity<String> httpEntity = new HttpEntity<String>(requestBody.toString(), httpHeaders);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("https://api.openai.com/v1/completions", httpEntity, String.class);
        // 获取返回体
        String response = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(response);
        // 解析JSON字符串
        JSONArray choices = jsonObject.getJSONArray("choices");
        String text = choices.getJSONObject(0).getString("text");
        return text;
    }

    @GetMapping("/api2")
    @ResponseBody
    public String chatByOpenaiJava(@RequestParam("que") String que) {
        String token = "你的API Key";
        OpenAiService service = new OpenAiService(token);
        CompletionRequest completionRequest = CompletionRequest.builder()
                .model("text-davinci-003")
                .prompt(que)
                .temperature(1.0)
                .maxTokens(2048)
                .topP(1D)
                .frequencyPenalty(0D)
                .presencePenalty(0D)
                .build();
        List<CompletionChoice> choices = service.createCompletion(completionRequest).getChoices();
        return choices.get(0).getText();
    }

    @GetMapping("/index")
    public String index() {
        return "index";
    }
}
